# # app1/xxl_job_client.py
import requests

# 统一返回格式
response_xxl_admin = {
    "code": 200,
    "msg": "",
    "content": "",
    "data": ""
}


def _format_response(code, msg="", data=None, content=""):
    """格式化返回结果"""
    response = response_xxl_admin.copy()
    response.update({
        "code": code,
        "msg": msg,
        "data": data,
        "content": content
    })
    return response


class XXLJobClient:
    def __init__(self, xxl_base_url, cookie=None):
        """
        初始化XXL-JOB客户端

        :param xxl_base_url: XXL-JOB管理端地址 (如: "http://localhost:8080/xxl-job-admin")
        :param cookie: 可选的初始cookie (支持完整cookie字符串或cookie值)
        """
        self.xxl_base_url = xxl_base_url.rstrip('/')
        self.session = requests.Session()

        if cookie:
            self._set_cookie(cookie)

    def _build_url(self, endpoint):
        """构建完整的请求URL"""
        return f"{self.xxl_base_url}/{endpoint.lstrip('/')}"

    def _set_cookie(self, cookie):
        """
            完全安全的cookie设置方法
            会清除所有同名cookie（无论domain/path如何）
            """
        cookie_name = "XXL_JOB_LOGIN_IDENTITY"

        # 解析cookie值
        if isinstance(cookie, dict):
            cookie_value = cookie.get(cookie_name)
        elif '=' in cookie:
            cookie_value = cookie.split('=')[1] if cookie.startswith(cookie_name) else None
        else:
            cookie_value = cookie

        if not cookie_value:
            raise ValueError(f"无效的cookie格式，必须包含{cookie_name}")

        # 彻底清除所有同名cookie（包括不同domain/path的）
        # 方法1：直接创建新的CookieJar（推荐）
        self.session.cookies = requests.cookies.RequestsCookieJar()

        # 方法2：遍历删除（如果方法1不适用）
        # for domain in list(self.session.cookies.list_domains()):
        #     for path in list(self.session.cookies.list_paths()):
        #         self.session.cookies.clear(domain, path, cookie_name)

        # 设置新cookie（使用默认domain/path）
        self.session.cookies.set(cookie_name, cookie_value)

    def login(self, username, password):
        """
        登录接口
        POST /login

        返回格式:
        {
            "code": 200,
            "msg": "登录成功",
            "content": "",
            "data": {
                "cookie_name": "XXL_JOB_LOGIN_IDENTITY",
                "cookie_value": "abc123",
                "full_cookie": "XXL_JOB_LOGIN_IDENTITY=abc123"
            }
        }
        """
        login_url = self._build_url("/login")
        form_data = {
            "userName": username,
            "password": password
        }

        try:
            resp = self.session.post(login_url, data=form_data)
            resp.raise_for_status()

            result = resp.json()
            if result.get("code") == 200:
                cookie = resp.cookies.get("XXL_JOB_LOGIN_IDENTITY")
                print("after login")
                print(self.session.cookies)
                return _format_response(
                    code=200,
                    msg="登录成功",
                    data={
                        "cookie_name": "XXL_JOB_LOGIN_IDENTITY",
                        "cookie_value": cookie,
                        "full_cookie": f"XXL_JOB_LOGIN_IDENTITY={cookie}"
                    }
                )
            return _format_response(
                code=result.get("code", 500),
                msg=result.get("msg", "登录失败")
            )
        except Exception as e:
            return _format_response(
                code=500,
                msg=f"登录请求失败: {str(e)}"
            )

    def trigger_job(self, job_id, executor_params=None, address_list=None, cookie=None):
        """
        触发任务执行
        POST /jobinfo/trigger

        返回格式:
        {
            "code": 200,
            "msg": "触发成功",
            "content": "",
            "data": {...}  # XXL-JOB原始返回
        }
        """
        if cookie:
            self._set_cookie(cookie)

        if not self.session.cookies.get("XXL_JOB_LOGIN_IDENTITY"):
            return _format_response(
                code=401,
                msg="未提供有效cookie"
            )

        trigger_url = self._build_url("/jobinfo/trigger")
        data = {"id": job_id}
        if executor_params:
            data["executorParams"] = executor_params
        if address_list:
            data["addressList"] = address_list

        try:
            resp = self.session.post(trigger_url, data=data)
            resp.raise_for_status()
            return _format_response(
                code=200,
                msg="触发成功",
                data=resp.json()
            )
        except Exception as e:
            return _format_response(
                code=500,
                msg=f"触发任务失败: {str(e)}"
            )

    def get_joblog_page(self, start=0, length=10, job_group=-1, job_id=-1, log_status=-1, cookie=None):
        """
        获取日志列表
        POST /joblog/pageList

        返回格式:
        {
            "code": 200,
            "msg": "",
            "content": "",
            "data": {
                "records": [...],
                "total": 100
            }
        }
        """
        if cookie:
            self._set_cookie(cookie)

        if not self.session.cookies.get("XXL_JOB_LOGIN_IDENTITY"):
            return _format_response(
                code=401,
                msg="未提供有效cookie"
            )

        page_url = self._build_url("/joblog/pageList")
        data = {
            "start": start,
            "length": length,
            "jobGroup": job_group,
            "jobId": job_id,
            "logStatus": log_status
        }

        try:
            resp = self.session.post(page_url, data=data)
            resp.raise_for_status()
            return _format_response(
                code=200,
                data=resp.json()
            )
        except Exception as e:
            return _format_response(
                code=500,
                msg=f"获取日志列表失败: {str(e)}"
            )

    def get_log_detail(self, log_id, from_line_num=1, cookie=None):
        """
        获取日志详情
        POST /joblog/logDetailCat

        返回格式:
        {
            "code": 200,
            "msg": "",
            "content": "",
            "data": {
                "fromLineNum": 1,
                "toLineNum": 100,
                "logContent": "...",
                "end": true
            }
        }
        """
        if cookie:
            self._set_cookie(cookie)

        if not self.session.cookies.get("XXL_JOB_LOGIN_IDENTITY"):
            return _format_response(
                code=401,
                msg="未提供有效cookie"
            )

        detail_url = self._build_url("/joblog/logDetailCat")
        data = {
            "logId": log_id,
            "fromLineNum": from_line_num
        }

        try:
            resp = self.session.post(detail_url, data=data)
            resp.raise_for_status()
            print("xxxxxxxxxxxxxx")
            print(resp.raise_for_status())
            print(resp.json())
            return _format_response(
                code=200,
                data=resp.json()
            )
        except Exception as e:
            return _format_response(
                code=500,
                msg=f"获取日志详情失败: {str(e)}"
            )

    # 其他接口保持相同模式...
    def get_jobinfo_page(self, start=0, length=10, job_group=2, triggerstatus=-1, job_desc="", executor_handler="",
                         cookie=None):
        """获取任务列表"""
        if cookie:
            self._set_cookie(cookie)

        if not self.session.cookies.get("XXL_JOB_LOGIN_IDENTITY"):
            return _format_response(
                code=401,
                msg="未提供有效cookie"
            )

        page_url = self._build_url("/jobinfo/pageList")
        data = {
            "start": start,
            "length": length,
            "jobGroup": job_group,
            "triggerStatus": triggerstatus
        }
        if job_desc:
            data["jobDesc"] = job_desc
        if executor_handler:
            data["executorHandler"] = executor_handler

        try:
            resp = self.session.post(page_url, data=data)
            resp.raise_for_status()
            return _format_response(
                code=200,
                data=resp.json()
            )
        except Exception as e:
            return _format_response(
                code=500,
                msg=f"获取任务列表失败: {str(e)}"
            )

    def get_jobgroup_page(self, start=0, length=10, cookie=None):
        """获取执行器列表"""
        if cookie:
            self._set_cookie(cookie)

        # 更安全的cookie检查方式
        cookies = [c for c in self.session.cookies if c.name == "XXL_JOB_LOGIN_IDENTITY"]
        if not cookies:
            return _format_response(401, "未提供有效cookie")

        # 确保只有一个有效cookie
        if len(cookies) > 1:
            self._set_cookie(cookies[0].value)  # 自动清理重复cookie

        page_url = self._build_url("/jobgroup/pageList")
        data = {
            "start": start,
            "length": length
        }

        try:
            resp = self.session.post(page_url, data=data)
            resp.raise_for_status()
            return _format_response(
                code=200,
                data=resp.json()
            )
        except Exception as e:
            return _format_response(
                code=500,
                msg=f"获取执行器列表失败: {str(e)}"
            )
